<?php
/**
 * @title 107. 二叉树的层次遍历 II - 迭代
 * @author start2004
 */

// ini_set("memory_limit", "128M");

class Solution {

    /**
     * @param TreeNode $root
     * @return Integer[][]
     */
    function levelOrderBottom($root) {
        /**
         * @since 2020-09-07 空树
         */
        if($root === null){
            return [];
        } else {}

        /**
         * @since 2020-09-07 结果集
         */
        $result = [];

        /**
         * @since 2020-09-07 每次迭代节点
         */
        $next = [$root];
        while($next){
            $nodes = [];
            $nextTmp = [];

            /**
             * @since 2020-09-07 遍历每个点
             */
            foreach ($next as $leaf){
                $nodes[] = $leaf->val;

                /**
                 * @since 2020-09-07 左右节点
                 */
                if($leaf->left !== null){
                    $nextTmp[] = $leaf->left;
                } else {}
                if($leaf->right !== null){
                    $nextTmp[] = $leaf->right;
                } else {}
            }

            /**
             * @since 2020-09-07 下次迭代
             */
            $result[] = $nodes;
            $next = $nextTmp;
        }

        /**
         * @return
         */
        return array_reverse($result);
    }
}



/**
 * @url http://127.0.0.1/leetcode/202009/2020.09.06.php
 */
$datas = [
    [3,9,20,null,null,15,7],
];

include_once dirname(__DIR__) . DIRECTORY_SEPARATOR ."xhprof.php";
$xhprof = new Xhprof();
foreach ($datas as $data){
    var_dump($data);

    $obj = new Solution();
    $result = $obj->levelOrderBottom($xhprof->tree($data));
    var_dump($result);
    // if(count($result)<=20){
    //     var_dump($result);
    // } else {
    //     var_dump(count($result));
    // }
    echo str_repeat("<br>", 3);
}

// foreach ($datas as $data){
//     $obj = new $data[0][0](...$data[1][0]);
//
//     for ($i=1; $i<count($data[0]); $i++){
//         $result = $obj->$data[0][$i](...$data[1][$i]);
//
//         echo $data[0][$i] ."(\"". $data[1][$i][0] ."\") ";
//             if($result === true){
//                 echo "True";
//             } elseif($result === false) {
//                 echo "False";
//             } elseif($result === null) {
//                 echo "Null";
//             } elseif(is_array($result)) {
//                 var_dump($result);
//             } else {
//                 echo $result;
//             }
//         echo PHP_EOL;
//     }
//
//     echo str_repeat(PHP_EOL, 3);
// }
$xhprof->end();
